package com.sgb.kjwl.view.ui.activity.leaseAsk.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentPublishLease1Binding;
import com.sgb.kjwl.model.entity.CarBrandEntity;
import com.sgb.kjwl.model.entity.PublishLeaseDataEntity;
import com.sgb.kjwl.model.entity.lease.AskLeaseItemEntity;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.model.entity.user.UnitEntity;
import com.sgb.kjwl.utils.EditInputFilter;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LeaseCarBrandEvent;
import com.sgb.alimaplibrary.SelectAddressActivity;
import com.sgb.kjwl.view.ui.activity.house.CarBrandActivity;
import com.sgb.kjwl.view.widget.TwoRangePopWindow;
import com.sgb.kjwl.viewmodel.machine.AskLeaseCommonModel;
import com.sgb.kjwl.viewmodel.machine.PublishLeaseInfoModel2;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PickSelectEntity;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


public class PublishLeashInfoFragment1 extends Fragment implements ItemInputTextView.OnWholeItemClickListener {

    private PublishLeaseInfoModel2 viewModel;
    private AskLeaseCommonModel commonModel;
    private FragmentPublishLease1Binding binding;
    private int type;//0机械,1设备,2车辆,3房产
    // 一级联动数据
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    // 二级联动数据
    private List<List<AddressEntity<List<AddressEntity>>>> opt2 = new ArrayList<>();
    // 三级联动数据
    private List<List<List<AddressEntity>>> opt3 = new ArrayList<>();

    private Calendar selectedDate, selectedDate2;
    private List<PickSelectEntity> classDatas = new ArrayList<>();
    private List<List<PickSelectEntity>> typeDatas = new ArrayList<>();

    private List<UnitEntity> UnitDatas = new ArrayList<>();
    private List<PickSelectEntity> limitTimeDatas = new ArrayList<>();
    private List<PickSelectEntity> driverDatas = new ArrayList<>();
    private List<PickSelectEntity> driverAgeDatas = new ArrayList<>();//驾龄
    private List<PickSelectEntity> leaseTimeDatas = new ArrayList<>();//租赁时长单位
    private List<DictEntity3> allpayway = new ArrayList<>();

    private ArrayList<PickSelectEntity> priceMatchUnitDatas = new ArrayList<>();
    private ArrayList<PickSelectEntity> cartypelist = new ArrayList<>();

    private String lat, lon, className, typeName, content;

    private final String labelName = "求租";
    private String id = "";

    private OptionsPickerView drivingAgeOpv, leaseTimeOpv;

    public void onAttach(Context context) {
        super.onAttach(context);
        id = getArguments().getString("id");
        type = getArguments().getInt("type");
    }

    public static PublishLeashInfoFragment1 newInstance(String id, int type) {
        PublishLeashInfoFragment1 frag = new PublishLeashInfoFragment1();
        Bundle bundle = new Bundle();
        bundle.putString("id", id);
        bundle.putInt("type", type);
        frag.setArguments(bundle);
        return frag;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_publish_lease_1, container, false);
        binding.setLifecycleOwner(this);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        viewModel = new ViewModelProvider(getActivity()).get(PublishLeaseInfoModel2.class);
        commonModel = new ViewModelProvider(this).get(AskLeaseCommonModel.class);
        recevierliveData();
        initView();
        initData();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void recevierliveData() {
        viewModel.initAddressDataLiveData.observe(getActivity(), t -> initAddressData(t));
        viewModel.showDetailLiveData.observe(getActivity(), t -> showDetail(t));
//        viewModel.showUnitLiveData.observe(getActivity(), t -> showUnit(t));
        viewModel.showTypeViewLiveData.observe(getActivity(), t -> showTypeView(t));
        viewModel.getAllPayWayLiveData.observe(getActivity(), t -> getAllPayWay(t));
        viewModel.getModelSelectListLiveData.observe(getActivity(), t -> getModelSelectList(t));
        viewModel.showVehicleSystemPickerLiveData.observe(getActivity(), t -> showVehicleSystemPicker(t));
        commonModel.driverAgeLiveData.observe(getActivity(), t -> driverAgeDatas.addAll(t));
        commonModel.leaseTimeUnitLiveData.observe(getActivity(), t -> {
            leaseTimeDatas.addAll(t);
            showLeaseTime();
        });

    }

    //返回省市区数据加载数据
    public void initAddressData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        addressEntityList = data;
        initJsonData();
    }

    //组装省市区数据信息
    private void initJsonData() {
        for (int i = 0; i < addressEntityList.size(); i++) {
            ArrayList areaList = new ArrayList<>();
            opt2.add(addressEntityList.get(i).getChildren());
            for (int j = 0; j < addressEntityList.get(i).getChildren().size(); j++) {
                List<AddressEntity> cityAreaList = new ArrayList<>();
                List<AddressEntity> children = addressEntityList.get(i).getChildren().get(j).getChildren();
                if (children == null || children.size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(children);
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
    }

    /**
     * 编辑回显 使用
     *
     * @param detailEditEntity
     */
    public void showDetail(PublishLeaseDataEntity detailEditEntity) {
        viewModel.bean = detailEditEntity;
        binding.itvType.setContent(detailEditEntity.getCategoryParentName() + "/" + detailEditEntity.getCategoryChildName());
        binding.machineryNumType.setText(detailEditEntity.getRentalUnit());
        switch (type) {
            case 0://机械
                binding.machineryDriver.setContent("0".equals(detailEditEntity.getIsDriver()) ? "是" : "否");
                binding.machineryDriver.setVisibility(View.VISIBLE);
                binding.machineryNum.setText(detailEditEntity.getRentalCount());
                if (!TextUtils.isEmpty(detailEditEntity.getBrandName())) {
                    binding.itvBrandNameMachinery.setContent(detailEditEntity.getBrandName());
                }
                if (!TextUtils.isEmpty(detailEditEntity.getModelName())) {
                    binding.itvModelNameMachinery.setContent(detailEditEntity.getModelName());
                }
                if (detailEditEntity.getIsDriver().equals("0")) {
                    binding.llDriverAge.setVisibility(View.VISIBLE);
                    binding.drivingAge.setVisibility(View.VISIBLE);
                } else {
                    binding.llDriverAge.setVisibility(View.GONE);
                    binding.drivingAge.setVisibility(View.GONE);
                }
                break;
            case 1://设备
                binding.machineryDriver.setContent("0".equals(detailEditEntity.getIsDriver()) ? "是" : "否");
                binding.machineryDriver.setVisibility(View.VISIBLE);
                binding.machineryNumType.setText(detailEditEntity.getRentalUnit());
                binding.machineryNum.setText(detailEditEntity.getRentalCount());
                if (!TextUtils.isEmpty(detailEditEntity.getBrandName())) {
                    binding.itvBrandNameMachinery.setContent(detailEditEntity.getBrandName());
                }
                if (!TextUtils.isEmpty(detailEditEntity.getModelName())) {
                    binding.itvModelNameMachinery.setContent(detailEditEntity.getModelName());
                }
                break;
            case 2://车辆
                binding.machineryNumType.setText(detailEditEntity.getRentalUnit());
                binding.itvType.setContent(detailEditEntity.getRentalModelName());
                binding.machineryNum.setText(detailEditEntity.getRentalCount());
                binding.itvBrandNameMachinery.setContent(detailEditEntity.getRentalBrandName());
                if (!TextUtils.isEmpty(detailEditEntity.getCarLineName())) {
                    binding.itemTvSeries.setContent(detailEditEntity.getCarLineName());
                }
                binding.itemTvBrand.setContent(detailEditEntity.getRentalBrandName());
                break;
        }
        binding.includeTime.leaseTime.setText(detailEditEntity.getRentalDuration());
        if (!TextUtils.isEmpty(detailEditEntity.getRentalDurationUnit())) {
            binding.includeTime.tvTimeUnit.setText(detailEditEntity.getRentalDurationUnit());
            binding.inLeasePrice.tvPriceUnit.setText("元/" + detailEditEntity.getRentalDurationUnit());
        }

        try {
            if (Double.parseDouble(detailEditEntity.getRentalPrice()) >= 0) {
                binding.inLeasePrice.rbPrice.setButtonDrawable(R.mipmap.lease_pub_unselect);
                binding.inLeasePrice.rbPrice.setChecked(false);
                detailEditEntity.setRentalPrice(detailEditEntity.getRentalPrice());
                binding.inLeasePrice.layoutPrice.setVisibility(View.VISIBLE);
                binding.inLeasePrice.rbPrice.setText("面议");
                binding.inLeasePrice.leasePrice.setText(detailEditEntity.getRentalPrice());

            } else {
                binding.inLeasePrice.rbPrice.setChecked(true);
                binding.inLeasePrice.rbPrice.setButtonDrawable(R.mipmap.lease_pub_select);
                binding.inLeasePrice.layoutPrice.setVisibility(View.GONE);
                binding.inLeasePrice.rbPrice.setText("您已选择面议，再次点击退出面议");
            }
        } catch (Exception exception) {
//            binding.inLeasePrice.rbPrice.setChecked(true);
//            binding.inLeasePrice.rbPrice.setButtonDrawable(R.mipmap.lease_pub_select);
//            binding.inLeasePrice.layoutPrice.setVisibility(View.GONE);
//            binding.inLeasePrice.rbPrice.setText("您已选择面议，再次点击退出面议");
        }
        binding.timeDeadline.setContent(DateUtils.stampToDay(detailEditEntity.getEndTime()));
        binding.timeCourse.setContent(DateUtils.stampToDay(detailEditEntity.getUseAndEnterTime()));
        binding.paymentMethod.setContent(detailEditEntity.getRentalPayMethod());
        binding.include.itemTvTitleEdit.setEditContent(detailEditEntity.getRentalTitle());
        binding.leaseUsername.setContent(detailEditEntity.getContactPerson());

        binding.address.setContent(detailEditEntity.getRentAddress().getTaskaddr());
        binding.itemTvPhone.setContent(detailEditEntity.getContactPhone());
        binding.leaseExpand.setEditContent(detailEditEntity.getRemark());
        if (!TextUtils.isEmpty(detailEditEntity.getDriverMinAge()) && !TextUtils.isEmpty(detailEditEntity.getDriverMaxAge())) {
            binding.age.setText(detailEditEntity.getDriverMinAge() + "-" + detailEditEntity.getDriverMaxAge());
        }
        if (!TextUtils.isEmpty(detailEditEntity.getDrivingAgeText())) {
            binding.drivingAge.setContent(detailEditEntity.getDrivingAgeText());
        }
        if (!TextUtils.isEmpty(detailEditEntity.getAircraftAge())) {
            binding.aircraftAge.setText(detailEditEntity.getAircraftAge());
        }
    }

    //类型集合
    public void showTypeView(List<AskLeaseItemEntity<List<AskLeaseItemEntity<List<AskLeaseItemEntity>>>>> data) {
        if (type == 0) {//机械
            for (AskLeaseItemEntity<List<AskLeaseItemEntity>> l : data.get(0).getChildren()) {
                PickSelectEntity entity = new PickSelectEntity();
                entity.setNo(l.getNo());
                entity.setProjectscale(l.getName());
                classDatas.add(entity);
                List<PickSelectEntity> childList = new ArrayList<>();
                for (AskLeaseItemEntity ll : l.getChildren()) {
                    PickSelectEntity child = new PickSelectEntity();
                    child.setNo(ll.getNo());
                    child.setProjectscale(ll.getName());
                    childList.add(child);
                }
                typeDatas.add(childList);
            }
        } else if (type == 1) {//设备
            for (AskLeaseItemEntity<List<AskLeaseItemEntity>> l : data.get(1).getChildren()) {
                PickSelectEntity entity = new PickSelectEntity();
                entity.setNo(l.getNo());
                entity.setProjectscale(l.getName());
                classDatas.add(entity);
                List<PickSelectEntity> childList = new ArrayList<>();
                for (AskLeaseItemEntity ll : l.getChildren()) {
                    PickSelectEntity child = new PickSelectEntity();
                    child.setNo(ll.getNo());
                    child.setProjectscale(ll.getName());
                    childList.add(child);
                }
                typeDatas.add(childList);
            }
        } else if (type == 2) {//车辆
            for (AskLeaseItemEntity<List<AskLeaseItemEntity>> l : data.get(2).getChildren()) {
                PickSelectEntity entity = new PickSelectEntity();
                entity.setNo(l.getNo());
                entity.setProjectscale(l.getName());
                classDatas.add(entity);
            }
        }
    }

    // 付款方式
    public void getAllPayWay(List<DictEntity3> data) {
        this.allpayway = data;
    }

    public void getLocationLL2() {
        Intent intent = new Intent();
        intent.setClass(getActivity(), SelectAddressActivity.class);
        intent.putExtra(SelectAddressActivity.TITLE, "工作地");
        intent.putExtra(SelectAddressActivity.HINT, "请输入地址");
        intent.putExtra(SelectAddressActivity.SAVE_TEXT, "确定");
        if (!TextUtils.isEmpty(lat) && !TextUtils.isEmpty(lon)) {
            intent.putExtra(SelectAddressActivity.LATITUDE, Double.parseDouble(lat));
            intent.putExtra(SelectAddressActivity.LONGTITUDE, Double.parseDouble(lon));
        }
        startActivityForResult(intent, 255);
    }

    //汽车类型数据列表选择
    public void getModelSelectList(List<DictEntity3> data) {
        for (int i = 0; i < data.size(); i++) {
            PickSelectEntity entity = new PickSelectEntity();
            entity.setNo(data.get(i).getId());
            entity.setProjectscale(data.get(i).getName());
            cartypelist.add(entity);
        }
    }

    /**
     * 展示车系列表弹窗
     *
     * @param carPositionList
     */
    public void showVehicleSystemPicker(List<DictEntity3> carPositionList) {
        if (carPositionList.size() > 0) {
            OptionsPickerView businessOption = new OptionsPickerBuilder(getActivity(), (options1, options2, options3, v) -> {
                String content = carPositionList.get(options1).getName();
                binding.itemTvSeries.setContent(content);
                viewModel.bean.setSeriesNo(carPositionList.get(options1).getId());
                viewModel.bean.setCarLineName(carPositionList.get(options1).getName());
                setDefaultTitle();
            }).build();
            businessOption.setPicker(carPositionList);
            businessOption.setSelectOptions(0);
            businessOption.show();
        } else {
            MToast.showToast(getActivity(), R.string.no_data);
        }
    }

    private void initView() {
        binding.setViewModel(viewModel);
        binding.setType(type);
        setContentItem();
        binding.nextItem.btNextStep.setOnClickListener(v -> {
            if (PublishLeaseData())
                viewModel.selectFragLiveData.postValue(1);
        });
        binding.nextItem.publicView.setOnClickListener(v -> {
            if (PublishLeaseData())
                viewModel.getequimentLeasing();
        });
        binding.includeTime.tvTimeUnit.setOnClickListener(v -> {//租赁时长
            if (leaseTimeOpv != null) {
                leaseTimeOpv.show();
            }
        });
        binding.includeTime.leaseTime.setFilters(new EditInputFilter[]{new EditInputFilter(99999999, 1, 0)});
        binding.machineryNum.setFilters(new EditInputFilter[]{new EditInputFilter(99999999, 1, 0)});//租赁数量

        binding.inLeasePrice.leasePrice.setFilters(new EditInputFilter[]{new EditInputFilter(99999999.99, 2)});
        binding.itvType.setOnWholeItemClickListener(this);
        binding.itvBrandNameMachinery.setOnWholeItemClickListener(this);
        binding.itemTvSeries.setOnWholeItemClickListener(this);

        binding.address.setOnWholeItemClickListener(this);
        binding.timeCourse.setOnWholeItemClickListener(this);
        binding.timeDeadline.setOnWholeItemClickListener(this);
        binding.machineryDriver.setOnWholeItemClickListener(this);
        binding.paymentMethod.setOnWholeItemClickListener(this);
        binding.machineryDriver.setOnWholeItemClickListener(this);
        binding.age.setOnClickListener(v -> twoRangePopWindow.showPopwindowBottom(binding.nextItem.btNextStep));
        binding.drivingAge.setOnWholeItemClickListener(this);
        binding.itemTvBrand.setOnWholeItemClickListener(this);
        binding.itemTvPhone.setInputType(InputType.TYPE_CLASS_PHONE);
        binding.include.tvUse.setOnClickListener(v -> binding.include.itemTvTitleEdit.setEditContent(binding.include.tvTitleDefault.getText().toString()));
        binding.include.rlLeaseTitle.setVisibility(View.GONE);
        binding.v.setVisibility(View.VISIBLE);

        //   面议还是报价功能
        binding.inLeasePrice.rbPrice.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                binding.inLeasePrice.rbPrice.setButtonDrawable(R.mipmap.lease_pub_select);
                binding.inLeasePrice.layoutPrice.setVisibility(View.GONE);
                binding.inLeasePrice.rbPrice.setText("您已选择面议，再次点击退出面议");
            } else {
                binding.inLeasePrice.rbPrice.setButtonDrawable(R.mipmap.lease_pub_unselect);
                binding.inLeasePrice.layoutPrice.setVisibility(View.VISIBLE);
                binding.inLeasePrice.leasePrice.setText("");
                binding.inLeasePrice.leasePrice.setHint("请输入(必填)");
                binding.inLeasePrice.rbPrice.setText("面议");
            }
        });
        binding.itvBrandNameMachinery.onTextChange(v -> setDefaultTitle());
        binding.itvModelNameMachinery.onTextChange(v -> setDefaultTitle());
        binding.address.setContentTextEnd();
        showAge();
        showDriverAge();
    }

    private void setContentItem() {
        switch (type) {
            case 0:
                binding.itvType.setLabelName("机械分类");
                binding.machineryDriver.setLabelName("是否自带驾驶员");
                binding.timeCourse.setLabelName("进场时间");
                binding.machineryDriver.setVisibility(View.VISIBLE);
                binding.timeCourse.setLabelHint("请选择进场时间");
                break;
            case 1:
                binding.itvType.setLabelName("设备分类");
                binding.machineryDriver.setLabelName("是否自带操作员");
                binding.timeCourse.setLabelName("进场时间");
                binding.machineryDriver.setVisibility(View.VISIBLE);
                binding.machineryDriver.setLabelName("是否自带操作员");
                binding.timeCourse.setLabelHint("请选择进场时间");
                break;
            case 2:
                binding.itvType.setLabelName("车辆分类");
                binding.timeCourse.setLabelName("使用时间");
                binding.timeCourse.setLabelHint("请选择使用时间");
                //车辆固定单位不需要选择，设置禁用
                binding.ivNumArrow.setVisibility(View.GONE);
                binding.llMachineryNumType.setClickable(false);
                break;
            default:
                break;
        }
    }

    private void initData() {
        lat = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.SelectLATITUDE, "");
        lon = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.SelectLONGITUDE, "");
        String contact = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.REAL_NAME, "");
        String loginPhone = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_PHONE, "");
        binding.leaseUsername.setContent(contact);
        binding.itemTvPhone.setContent(loginPhone);

        selectedDate = Calendar.getInstance();
        selectedDate2 = Calendar.getInstance();
        viewModel.getAddressModel();//请求省市区数据
        viewModel.getTypeModel();//数据类型
        viewModel.getAllPayWay();//付款方式
        commonModel.getDriverAgeDatas();
        commonModel.getLeaseTimeUnit(type + "");//获取租赁时长单位
        if (type == 2) {
            viewModel.getModelSelect();//汽车分类
        }

        for (int i = 1; i < 30; i++) {
            PickSelectEntity timedentity = new PickSelectEntity();
            timedentity.setNo("" + i);
            timedentity.setProjectscale(i + "天");
            limitTimeDatas.add(timedentity);
        }
        //是否带驾驶员（0:是;1:否）
        PickSelectEntity dentity = new PickSelectEntity();
        dentity.setNo("0");
        dentity.setProjectscale("是");
        PickSelectEntity dentity1 = new PickSelectEntity();
        dentity1.setNo("1");
        dentity1.setProjectscale("否");
        driverDatas.add(dentity);
        driverDatas.add(dentity1);
        // TODO: 2020/8/20
        viewModel.bean.setIsDriver("0");
        binding.machineryDriver.setContent("是");
        String[] priceMatchUnit = new String[]{"台", "辆"};
        for (int i = 1; i < 3; i++) {
            PickSelectEntity timedentity = new PickSelectEntity();
            timedentity.setNo("" + i);
            timedentity.setProjectscale(priceMatchUnit[i - 1]);
            priceMatchUnitDatas.add(timedentity);
        }
        if (type != 2) {
            binding.llMachineryNumType.setOnClickListener(v -> showMatchPriceUnitPop());
        }
        binding.machineryNumType.setText("辆");
        viewModel.bean.setRentalUnit("辆");
        if (!TextUtils.isEmpty(id)) {
            viewModel.getDeviceDetail(id, String.valueOf(type));
        }
    }

    //监听车辆品牌界面发送的选择结果
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LeaseCarBrandEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_CAR_BRAND_SELECT) {
            CarBrandEntity brandEntity = (CarBrandEntity) event.getMessageData();
            viewModel.bean.setRentalBrandId(brandEntity.getId());
            //选择品牌的时候重置车系数据
            binding.itemTvBrand.setContent(brandEntity.getName());
            binding.itemTvSeries.setContent("");
            binding.itemTvSeries.setHint("请输入车系(必填)");
            setDefaultTitle();
        }
    }

    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
            case R.id.itv_type://租赁类型
                if (type == 2) {
                    showcarTypePop();
                } else {
                    showClassTypePop();
                }
                break;
            case R.id.item_tv_brand://车辆品牌
                CarBrandActivity.start(getActivity());
                break;
            case R.id.item_tv_series://获取车系列表
                if (TextUtils.isEmpty(binding.itemTvBrand.getContent())) {
                    MToast.showToast(getActivity(), "请选择车辆品牌");
                    return;
                }
                viewModel.getCarSeries(viewModel.bean.getRentalBrandId());
                break;
            case R.id.address:
                getLocationLL2();
                break;
            case R.id.time_course://使用时间(进场时间)
                showCourseTimePop();
                break;
            case R.id.time_deadline://报价截止时间
                if (TextUtils.isEmpty(binding.timeCourse.getContent())) {
                    if (type == 0 || type == 1) {
                        MToast.showToast(getActivity(), "请选择进场时间");
                    } else {
                        MToast.showToast(getActivity(), "请选择使用时间");
                    }
                    return;
                }
                if (null != limitTimeDatas && limitTimeDatas.size() > 0) {
                    showLimitTimePop();
                }
                break;
            case R.id.machinery_driver://是否携带驾驶员
                showDriverPop();
                break;
            case R.id.payment_method://付款方式选择
                showPaymentMethodPop();
                break;
            case R.id.driving_age://驾龄
                drivingAgeOpv.show();
                break;
            default:
                break;

        }
    }

    public static void hideKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    //发布数据
    private boolean PublishLeaseData() {
        if (!TextUtils.isEmpty(binding.itemTvPhone.getContent())) {
            if (!CheckUtils.isPhoneNumberValid(binding.itemTvPhone.getContent().trim())) {
                MToast.showToast(getActivity(), "请填写正确的联系电话");
                return false;
            }
        }

        if (TextUtils.isEmpty(binding.itvType.getContent())) {
            if (type == 0) {
                MToast.showToast(getActivity(), "请选择机械分类");
            } else if (type == 1) {
                MToast.showToast(getActivity(), "请选择设备分类");
            } else {
                MToast.showToast(getActivity(), "请选择车辆分类");
            }
            return false;
        }

        viewModel.bean.setRentalUnit(binding.machineryNumType.getText().toString().trim());
        viewModel.bean.setRentalCount(binding.machineryNum.getText().toString().trim());

        if (type == 0 || type == 1) {
            viewModel.bean.setBrandName(binding.itvBrandNameMachinery.getContent());
            viewModel.bean.setModelName(binding.itvModelNameMachinery.getContent());
        }

        if (TextUtils.isEmpty(binding.address.getContent().trim())) {
            MToast.showToast(getActivity(), "请选择工作地");
            return false;
        }
        if (lat == null || lon == null) {
            MToast.showToast(getActivity(), "经纬度不能为空");
            return false;
        }

        if (!TextUtils.isEmpty(binding.timeDeadline.getContent()) && !TextUtils.isEmpty(binding.timeCourse.getContent())) {
            if (checkDate(binding.timeDeadline.getContent(), binding.timeCourse.getContent())) {//使用时间和截止时间校验
                return false;
            }
        }

        if (binding.inLeasePrice.rbPrice.isChecked()) {
            viewModel.bean.setRentalPrice("-1");
            viewModel.bean.setRentalSelectPrice("");
        } else {
            String price = binding.inLeasePrice.leasePrice.getText().toString().trim();
            if (!TextUtils.isEmpty(price)) {
                if (Double.parseDouble(price) <= 0) {
                    MToast.showToast(getActivity(), "请填写大于0的期望租金");
                    return false;
                }
            }
            viewModel.bean.setRentalPrice(price);
        }

        //设置标题参数
        if (!TextUtils.isEmpty(binding.include.itemTvTitleEdit.getEditContent().trim())) {
            viewModel.bean.setRentalTitle(binding.include.itemTvTitleEdit.getEditContent().trim());
        } else {
            MToast.showToast(getActivity(), "请填写业务名称");
            return false;
        }

        viewModel.bean.setCategoryType(type + "");
        viewModel.bean.setContactPerson(binding.leaseUsername.getContent());
        viewModel.bean.setContactPhone(binding.itemTvPhone.getContent());
        viewModel.bean.setRemark(binding.leaseExpand.getEditContent());
        viewModel.bean.setAircraftAge(binding.aircraftAge.getText().toString().trim());
        viewModel.bean.setRentalDuration(binding.includeTime.leaseTime.getText().toString().trim());
        return true;
    }

    //日期比较
    private boolean checkDate(String startTime, String endTime) {
        try {
            if (DateUtils.dateTo13Timestamp(endTime) < DateUtils.dateTo13Timestamp(startTime) || startTime.equals(endTime)) {
                if (type == 1 || type == 2) {
                    MToast.showToast(getActivity(), "请选择小于进场时间的日期");
                } else {
                    MToast.showToast(getActivity(), "请选择小于使用时间的日期");
                }
                return true;
            }
        } catch (Exception e) {
        }
        return false;
    }

    //动态设置设置默认标题
    private void setDefaultTitle() {
        switch (type) {
            case 2:
                StringBuilder stringBuilder1 = new StringBuilder("求租");
                if (!TextUtils.isEmpty(classNamec)) {//车辆类型
                    stringBuilder1.append(classNamec);
                }
                if (!TextUtils.isEmpty(binding.itemTvBrand.getContent())) {//品牌
                    stringBuilder1.append(binding.itemTvBrand.getContent());
                }
                if (!TextUtils.isEmpty(binding.itemTvSeries.getContent())) {//车系
                    stringBuilder1.append(binding.itemTvSeries.getContent());
                }
                binding.include.tvTitleDefault.setText(stringBuilder1.toString());
                break;
            default:
                StringBuilder stringBuilder = new StringBuilder("求租");
                if (!TextUtils.isEmpty(binding.itvBrandNameMachinery.getContent())) {//品牌
                    stringBuilder.append(binding.itvBrandNameMachinery.getContent());
                }
                if (!TextUtils.isEmpty(binding.itvModelNameMachinery.getContent())) {//型号
                    stringBuilder.append(binding.itvModelNameMachinery.getContent());
                }
                if (!TextUtils.isEmpty(typeName)) {//机械二级分类
                    stringBuilder.append(typeName);
                }
                binding.include.tvTitleDefault.setText(stringBuilder.toString());
                break;
        }
        binding.include.rlLeaseTitle.setVisibility(View.VISIBLE);
        binding.v.setVisibility(View.GONE);
    }

    private String classNamec;

    //    车辆类型的选择
    private void showcarTypePop() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(getActivity(), (options1, options2, options3, v) -> {
            classNamec = cartypelist.get(options1).getProjectscale();
            binding.itvType.setContent(classNamec);
            viewModel.bean.setRentalModelId(cartypelist.get(options1).getNo() + "");
            setDefaultTitle();
        }).build();
        businessOption.setPicker(cartypelist);
        businessOption.setSelectOptions(0);
        businessOption.show();
    }

    //    机械、设备、车辆、房产分类
    private void showClassTypePop() {
        if (classDatas == null || classDatas.size() == 0) return;
        OptionsPickerView businessOption = new OptionsPickerBuilder(getActivity(), (options1, options2, options3, v) -> {
            className = classDatas.get(options1).getProjectscale();
            viewModel.bean.setCategoryParentId(classDatas.get(options1).getNo());
            if (typeDatas.size() == 0 || null == typeDatas.get(options1) || typeDatas.get(options1).size() == 0 || typeDatas.get(options1).get(options2) == null) {

            } else {
                typeName = typeDatas.get(options1).get(options2).getProjectscale();
            }

            if (!TextUtils.isEmpty(typeName)) {
                binding.itvType.setContent(className + " " + typeName);
                viewModel.bean.setCategoryParentId(classDatas.get(options1).getNo() + "");
                viewModel.bean.setCategoryChildId(typeDatas.get(options1).get(options2).getNo() + "");
                binding.include.tvTitleDefault.setText(labelName + " " + className + "/" + typeName);
            } else {
                binding.itvType.setContent(className + "");
                viewModel.bean.setCategoryChildId("");
                binding.include.tvTitleDefault.setText(labelName + "" + className);
            }

            setDefaultTitle();

        }).build();
        businessOption.setPicker(classDatas, typeDatas);
        businessOption.setSelectOptions(0, 0);
        businessOption.show();
    }


    //进场时间
    private void showCourseTimePop() {
        Calendar dayCalendar = Calendar.getInstance();
        dayCalendar.setTime(new Date());
        dayCalendar.add(Calendar.DAY_OF_MONTH, 1);

        TimePickerView timePicker = new TimePickerBuilder(getActivity(), (date, v) -> {
            @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(date);
            try {
                binding.timeCourse.setContent(format);
                viewModel.bean.setUseAndEnterTime(DateUtils.dateTo13Timestamp(format + " 23:59:59") + "");
                selectedDate2.setTime(date);
                binding.timeDeadline.setContent("");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).setType(new boolean[]{true, true, true, false, false, false})
                .setCancelText("取消").setSubCalSize(15)
                .setCancelColor(Color.parseColor("#666666"))
                .setTitleText("请选择时间")
                .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(Color.parseColor("#5792FD"))
                .setRangDate(dayCalendar, null)
                .build();
        timePicker.show();
        timePicker.setDate(selectedDate2);
    }

    //报价截止时间
    private void showLimitTimePop() {
        TimePickerView timePicker = new TimePickerBuilder(getActivity(), (date, v) -> {
            try {
                @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String format = sdf.format(date);
                if (checkDate(format, binding.timeCourse.getContent())) {
                    return;
                }
                viewModel.bean.setEndTime(DateUtils.dateTo13Timestamp3(format + " 23:59:59") + "");
                binding.timeDeadline.setContent(format);
                selectedDate.setTime(date);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).setType(new boolean[]{true, true, true, false, false, false})
                .setCancelText("取消").setSubCalSize(15)
                .setCancelColor(Color.parseColor("#666666"))
                .setTitleText("请选择时间")
                .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(Color.parseColor("#5792FD"))
                .setRangDate(Calendar.getInstance(), null)
                .build();
        timePicker.show();
        timePicker.setDate(selectedDate);
    }

    //   是否携带驾驶员
    private void showDriverPop() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(getActivity(), (options1, options2, options3, v) -> {
            String content = driverDatas.get(options1).getProjectscale();
            viewModel.bean.setIsDriver(driverDatas.get(options1).getNo() + "");
            binding.machineryDriver.setContent(content);
            if (content.equals("是")) {
                if (type == 0) {
                    binding.llDriverAge.setVisibility(View.VISIBLE);
                    binding.vDriver.setVisibility(View.VISIBLE);
                    binding.drivingAge.setVisibility(View.VISIBLE);
                }
            } else {
                if (type == 0) {
                    binding.llDriverAge.setVisibility(View.GONE);
                    binding.vDriver.setVisibility(View.GONE);
                    binding.drivingAge.setVisibility(View.GONE);
                    viewModel.bean.setDriverMinAge("");//年龄清空
                    viewModel.bean.setDriverMaxAge("");
                    binding.age.setText("");

                    viewModel.bean.setDrivingYears("");//驾龄清空
                    binding.drivingAge.setContent("");
                }
            }
        }).build();
        businessOption.setPicker(driverDatas);
        businessOption.setSelectOptions(0);
        businessOption.show();
    }

    //付款方式选择
    private void showPaymentMethodPop() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(getActivity(), (options1, options2, options3, v) -> {
            String content = allpayway.get(options1).getName();
            //2020/8/20修改
            viewModel.bean.setRentalPayMethod(content + "");
            binding.paymentMethod.setContent(content);
        }).build();
        businessOption.setPicker(allpayway);
        businessOption.setSelectOptions(0);
        businessOption.show();
    }

    //    选择租赁数量的单价
    private void showMatchPriceUnitPop() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(getActivity(), (options1, options2, options3, v) -> {
            String content = priceMatchUnitDatas.get(options1).getProjectscale();
            binding.machineryNumType.setText(content);
        }).build();
        businessOption.setPicker(priceMatchUnitDatas);
        businessOption.setSelectOptions(0);
        businessOption.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) {
            if (requestCode == 255 && data != null) {
                String lat = data.getDoubleExtra(SelectAddressActivity.LATITUDE, 0) + "";
                String lon = data.getDoubleExtra(SelectAddressActivity.LONGTITUDE, 0) + "";
                String address = data.getStringExtra(SelectAddressActivity.CURRENT_POSITION);
                PublishLeaseDataEntity.RentAddress rentAddress = viewModel.bean.getRentAddress();
                rentAddress.setLatitude(lat);
                rentAddress.setLongitude(lon);
                rentAddress.setTaskaddr(address);
                viewModel.bean.setRentAddress(rentAddress);
                binding.address.setContent(address);
            }
        }
    }

    private TwoRangePopWindow twoRangePopWindow;

    private void showAge() {
        twoRangePopWindow = new TwoRangePopWindow(getActivity());
        twoRangePopWindow.setOnCallBack((startTime, endTime, content) -> {
            if (startTime < endTime) {
                viewModel.bean.setDriverMinAge(String.valueOf(startTime));
                viewModel.bean.setDriverMaxAge(String.valueOf(endTime));
                binding.age.setText(content);
                twoRangePopWindow.dismiss();
            } else {
                MToast.showToast(getActivity(), "最大年龄必须大于等于最小年龄");
            }
        });
        twoRangePopWindow.setData(commonModel.getAgeData(18, 59), commonModel.getAgeData(19, 60));
        twoRangePopWindow.setCurrentItem(0, 21);
        twoRangePopWindow.setBgView(binding.grayLayout);
        twoRangePopWindow.setTitle("驾驶员年龄");
    }


    /**
     * 驾驶员年龄
     */

    private void showDriverAge() {
        drivingAgeOpv = new OptionsPickerBuilder(getActivity(), (options1, options2, options3, v) -> {
            String content = driverAgeDatas.get(options1).getProjectscale();
            viewModel.bean.setDrivingYears(driverAgeDatas.get(options1).getNo());
            binding.drivingAge.setContent(content);
            drivingAgeOpv.setSelectOptions(options1);
        }).build();
        drivingAgeOpv.setPicker(driverAgeDatas);
        drivingAgeOpv.setSelectOptions(0);
    }

    /**
     * 租赁时长
     */
    private void showLeaseTime() {
        leaseTimeOpv = new OptionsPickerBuilder(getActivity(), (options1, options2, options3, v) -> {
            String content = leaseTimeDatas.get(options1).getProjectscale();
            String no = leaseTimeDatas.get(options1).getNo();
            binding.includeTime.tvTimeUnit.setText(content);
            viewModel.bean.setRentalDurationUnit(content);
            viewModel.bean.setRentalDurationUnitNo(no);
            binding.inLeasePrice.tvPriceUnit.setText("元/" + content);
        }).build();
        leaseTimeOpv.setPicker(leaseTimeDatas);
        leaseTimeOpv.setSelectOptions(0);
        if (leaseTimeDatas.size() > 0) {
            if (TextUtils.isEmpty(viewModel.bean.getRentalDurationUnitNo())) {//为了防止租赁时长接口最后返回数覆盖了编辑的数据
                String unit = leaseTimeDatas.get(0).getProjectscale();
                viewModel.bean.setRentalDurationUnit(unit);
                viewModel.bean.setRentalDurationUnitNo(leaseTimeDatas.get(0).getNo());
                binding.includeTime.tvTimeUnit.setText(unit);
                binding.inLeasePrice.tvPriceUnit.setText("元/" + unit);
            }
        }
    }

}
